package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.BasePlan;
import com.yegs.jltqc.VO.BaseQuota;
import com.yegs.jltqc.VO.ProjectEntity;
import com.yegs.jltqc.common.StoreException;
import com.yegs.jltqc.dao.BasePlanRepository;
import com.yegs.jltqc.dao.BaseQuotaRepository;
import com.yegs.jltqc.dao.ProjectEntityRepository;
import com.yegs.jltqc.dao.ProjectRepository;
import com.yegs.jltqc.service.BasePlanService;
import com.yegs.jltqc.service.BaseQuotaService;
import com.yegs.jltqc.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BaseQuotaServiceImpl implements BaseQuotaService {

    @Autowired
    private ProjectEntityRepository projectEntityRepository;

    @Autowired
    private BaseQuotaRepository baseQuotaRepository;

    @Override
    public void save(BaseQuota baseQuota) {
        if(baseQuota.getId() == null){
            BaseQuota quota = baseQuotaRepository.findBaseQuotaByNameAndAndRefId(baseQuota.getName(), baseQuota.getRefId());
            if( quota != null){
                throw new StoreException("名称重复!");
            }
        }
        baseQuotaRepository.save(baseQuota);
    }

    @Override
    public List<BaseQuota> list() {
        return baseQuotaRepository.findAll();
    }

    @Override
    public BaseQuota get(Long id) {
        return baseQuotaRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        List<ProjectEntity> list = projectEntityRepository.findProjectEntitiesByQuotaId(id);
        if(list.size() > 0){
            throw new StoreException("已经被项目引用，不可删除");
        }
        baseQuotaRepository.deleteById(id);
    }

    @Override
    public Page<BaseQuota> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return baseQuotaRepository.findAll(request);
        }
        return baseQuotaRepository.findBaseQuotaByNameLike(query.getName(), request);
    }

}


